package cn.org.timespace.plat.socket.util;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;

import cn.org.timespace.plat.socket.mina.server.MinaESPlatServer;

public class MinaPlatUtil {

	/**
	 * 根据远程连接信息获取IP和端口
	 * @param inetSocketAddress
	 * @return
	 */
	public static String getIpPort(InetSocketAddress inetSocketAddress) {
		return inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort();
	}
	
	/**
	 * 同步当前连接中的远端IP与保存在session中的远端IP
	 * @param session
	 */
	public static void synSession(IoSession session) {
		String ipPort = getIpPort((InetSocketAddress)session.getRemoteAddress());
		
		String ipPortSession = (String) session.getAttribute("ipPort");
		
		if(ipPortSession != null && !ipPort.equals(ipPortSession))
			session.setAttribute("ipPort", ipPort);
	}
	
	/**
	 * 关闭同一信息机的其他Session，并记录其他Session个数
	 * @param machineNo
	 * @param currSession
	 */
	public static int closeOtherSessionByMachineNo(String machineNo, IoSession currSession) {
		IoAcceptor acceptor = MinaESPlatServer.getAcceptor();
		
		IoSession session;
		String machineNoInSession;
		
		int otherSessionCount = 0;
		
		String machineNoInCurrSession = (String) currSession.getAttribute("MachineNo");
		
		Map<Long, IoSession> conMap = acceptor.getManagedSessions();
		
		Iterator<Long> iter = conMap.keySet().iterator();
		while (iter.hasNext()) {
			Long key = iter.next();
			session = (IoSession)conMap.get(key);
			
			machineNoInSession = (String) session.getAttribute("MachineNo");
			if(machineNoInSession != null && currSession.getId() != session.getId() && machineNoInSession.equals(machineNoInCurrSession)) {
				session.setAttribute("closeFlag", "0");//正常关闭
				session.close(true);
				otherSessionCount++;
			}
		}
		
		return otherSessionCount;
	}
}
